//
//  XQWelcomeController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/3.
//

import UIKit

class XQWelcomeController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource {
    
    var imageArr : [String] = ["welcome_1","welcome_2","welcome_3"]
    
    var selectIndex : Int = 0
    
    private lazy var collectionView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = self.view.bounds.size
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.bounces = false
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.register(XQWelcomeCell.self, forCellWithReuseIdentifier: "XQWelcomeCell")
        return collectionView
    }()
    
    var launchOptions : [UIApplication.LaunchOptionsKey: Any]?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.collectionView)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imageArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XQWelcomeCell", for: indexPath) as! XQWelcomeCell
        cell.setImageName(name: imageArr[indexPath.item])
        cell.setIsLast(isLast: indexPath.item == self.imageArr.count - 1)
        cell.nextHandle = {[weak self] in
            guard let sronfigy = self else {return}
            sronfigy.clickAtIndexPath(indexPath: indexPath)
        }
        return cell
    }
    
    func clickAtIndexPath(indexPath : IndexPath) {
        selectIndex += 1
        if (selectIndex == self.imageArr.count) {
            
            let mainVC = XQMainTabBarController()
            self.navigationController?.setViewControllers([mainVC], animated: false)
            
            XQCache.saveShowGuide(show: true)
            return
        }

        self.collectionView.setContentOffset(CGPoint(x: CGFloat(selectIndex) * UIScreen.main.bounds.width, y: 0), animated: true)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let dx = scrollView.contentOffset.x
        let index = dx / UIScreen.main.bounds.width
        selectIndex = Int(index)
    }

}
